/******************************************************************************************************
Copyright (C) 2013 Mestrelab Research S.L. All rights reserved.

This file is part of the Mnova scripting toolkit.

Authorized users of Mnova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/

/*globals Application, MnUi*/
/*jslint plusplus: true, indent: 4*/

// Applies to the spectra of a stacked item the same phase as the one from the current spectrum in the item
function samePhaseAsCurrent(aSpec) {
	"use strict";

	var proc, curSpecIndex, i, d,
		ph0 = {},
		ph1 = {};

	if (aSpec === undefined) {
		aSpec = Application.nmr.activeSpectrum();
	}

	curSpecIndex = aSpec.curSpecIndex;
	try {
		proc = aSpec.proc;
		for (d = 1; d <= aSpec.dimCount; d++) {
			ph0[d] = proc.getParameter("PC[{0}].Ph0".format(d));
			ph1[d] = proc.getParameter("PC[{0}].Ph1".format(d));
		}
		for (i = 0; i < aSpec.specCount; i++) {
			if (i !== curSpecIndex) {
				aSpec.curSpecIndex = i;
				proc = aSpec.proc;
				for (d = 1; d <= aSpec.dimCount; d++) {
					proc.setParameter("PC[{0}].Method".format(d), "Manual");
					proc.setParameter("PC[{0}].Ph0".format(d), ph0[d]);
					proc.setParameter("PC[{0}].Ph1".format(d), ph1[d]);
				}
				aSpec.processCurSpec();
			}
		}
	} finally {
		aSpec.curSpecIndex = curSpecIndex;
		aSpec.update();
		Application.mainWindow.activeDocument.update();
	}
}

if (this.MnUi && MnUi.scripts_nmr) {
	MnUi.scripts_nmr.scripts_nmr_SamePhaseAsCurrent = samePhaseAsCurrent;
}
